﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace To {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e) {
            initSocket();
        }
        IPHostEntry ipHost;
        IPAddress[] ipAddrs;
        IPEndPoint ipEndPoint;
        Socket sListener;
        bool run = true;
        public void initSocket() {

            // establish the local end point for the socket 
            ipHost = Dns.GetHostEntry("127.0.0.1");
            ipAddrs = new IPAddress[ipHost.AddressList.Length];
            // use only IPv4
            int z = 0;
            for (int i = 0; i < ipHost.AddressList.Length; i++) {
                if (ipHost.AddressList[i].AddressFamily == AddressFamily.InterNetwork) {
                    ipAddrs[z++] = ipHost.AddressList[i];
                }
            }


            // bind the socket to the local endpoint and 
            // listen to the incoming sockets 

            Thread ths = new Thread(new ThreadStart(ListenBind));
            ths.Start();
        } // end of init 

        public void ListenBind() {
            try {

                TcpListener listener = new TcpListener(IPAddress.Any, 11000);
                listener.Start();
                while (!listener.Pending())
                    Thread.Sleep(1);
               
                //IPAddress ipAddr = ipHost.AddressList[0];
                ipEndPoint = new IPEndPoint(IPAddress.Any, 11000);

                // create a Tcp/Ip Socket 
                //sListener = new Socket(AddressFamily.InterNetwork,
                //                             SocketType.Stream, ProtocolType.Tcp);
                //sListener.Bind(ipEndPoint);
                //sListener.Listen(10);
                Socket handler = listener.AcceptSocket();
                //listener.Stop();
                // Start listening for connections 

                do {
                    Invoke(new MethodInvoker(delegate {
                        textBox1.Text += "Waiting for a connection on port " + ipEndPoint + Keys.Enter;
                    }));

                    // program is suspended while waiting for an incoming connection 

                    
                    NetworkStream ns = new NetworkStream(handler);

                    // we got the client attempting to connect 
                    Stopwatch sw = new Stopwatch();
                    while (run)
                        if (ns.DataAvailable && run) {
                            sw.Start();
                            BinaryFormatter outFormatter = new BinaryFormatter();
                            pictureBox1.Image = (Image)outFormatter.Deserialize(ns);
                            sw.Stop();
                            MessageBox.Show(sw.ElapsedMilliseconds.ToString());
                            sw.Reset();
                        }
                        else Thread.Sleep(1);


                    // show the data on the console 
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                } while (run);
            }
            catch (Exception e) {
                Invoke(new MethodInvoker(delegate {
                    textBox1.Text += e.ToString() + Keys.Enter;
                }));
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
            run = false;
        }
    }
}